package com.xie.authority_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xie.authority_system.dao.RoleMapper;
import com.xie.authority_system.entity.Role;
import com.xie.authority_system.entity.User;
import com.xie.authority_system.service.RoleService;
import com.xie.authority_system.service.UserService;
import com.xie.authority_system.vo.query.RoleQueryVo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author XIEJINGCHENG
 * @description 针对表【sys_role(角色表)】的数据库操作Service实现
 * @createDate 2024-01-08 14:45:27
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private UserService userService;

    /**
     * 根据用户Id来查询角色列表
     * @param page
     * @param roleQueryVo
     * @return
     */
    @Override
    public void findRoleListByUserId(IPage<Role> page, RoleQueryVo roleQueryVo) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!ObjectUtils.isEmpty(roleQueryVo.getRoleName()),"role_name", roleQueryVo.getRoleName());
        queryWrapper.orderByAsc("id");
        User user = userService.getById(roleQueryVo.getUserId());
        if (user!=null && !ObjectUtils.isEmpty(user.getIsAdmin()) && user.getIsAdmin() != 1) {
            queryWrapper.eq("create_user", roleQueryVo.getUserId());
        }

        baseMapper.selectPage(page, queryWrapper);
    }

    /**
     * 判断该角色已被使用
     * @param id
     * @return
     */
    @Override
    public boolean hasRoleCount(Long id) {
        return baseMapper.getRoleCountByRoleId(id) > 0;
    }

    /**
     * 根据id删除角色
     * @param id
     * @return
     */
    @Override
    public boolean deleteRoleById(Long id) {
        // 删除角色对应的权限列表
        baseMapper.deleteRolePermissionByRoleId(id);
        return baseMapper.deleteById(id) > 0;
    }

    /**
     * 保存角色权限信息
     * @param roleId
     * @param permissionIds
     * @return
     */
    @Override
    public boolean saveRolePermission(Long roleId, List<Long> permissionIds) {
        // 删除角色对应的权限列表
        baseMapper.deleteRolePermissionByRoleId(roleId);
        // 保存角色权限信息
        return baseMapper.saveRolePermission(roleId, permissionIds) > 0;
    }

    /**
     * 根据用户id查询该用户拥有的角色id
     * @param userId
     * @return
     */
    @Override
    public List<Long> findRoleIdByUserId(Long userId) {
        return baseMapper.findRoleIdByUserId(userId);
    }
}




